package com.szqhyxj.youxiangju.biz.web;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.szqhyxj.youxiangju.BaseActivity;
import com.szqhyxj.youxiangju.BuildConfig;
import com.szqhyxj.youxiangju.R;
import com.szqhyxj.youxiangju.biz.core.TokenManager;
import com.szqhyxj.youxiangju.biz.login.LoginActivity;
import com.szqhyxj.youxiangju.biz.merchantHome.MerchantContainerActivity;
import com.szqhyxj.youxiangju.biz.merchantHome.MerchantType;
import com.szqhyxj.youxiangju.biz.merchantHome.shop.purchase.PreparePurchaseActivity;
import com.szqhyxj.youxiangju.biz.onlineChannel.OnlineChannelListActivity;
import com.szqhyxj.youxiangju.biz.set.SettingActivity;
import com.szqhyxj.youxiangju.sys.components.NavigationBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WebActivity extends BaseActivity implements NavigationBar.NavigationBarListener {

    @BindView(R.id.navigationBar)
    NavigationBar navigationBar;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.web)
    MyWebView web;
    private static final String EXIT = "exit";

    private int exit = 9;

    public static void startToH5(Activity activity, String path) {
        String host = BuildConfig.H5_HOST + path;
        Intent intent = new Intent();
        intent.setClass(activity, WebActivity.class);
        intent.putExtra("url", host);
        activity.startActivity(intent);
    }

    public static void startToH5(Activity activity, String path, int exit) {
        String host = BuildConfig.H5_HOST + path;
        Intent intent = new Intent();
        intent.setClass(activity, WebActivity.class);
        intent.putExtra("url", host);
        intent.putExtra(EXIT, exit);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, String url) {
        Intent intent = new Intent();
        intent.setClass(activity, WebActivity.class);
        intent.putExtra("url", url);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, String title, String url) {
        Intent intent = new Intent();
        intent.setClass(activity, WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", title);
        activity.startActivity(intent);
    }

    public static void startToH5(Activity activity, String title, String path) {
        String host = BuildConfig.H5_HOST + path;
        Intent intent = new Intent();
        intent.setClass(activity, WebActivity.class);
        intent.putExtra("url", host);
        intent.putExtra("title", title);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        ButterKnife.bind(this);

        initViews();
        initDatas();
        initEvent();
        gainCurrenTime();
        exit = getIntent().getIntExtra(EXIT, 9);

    }

    private void initViews() {
        this.web.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                sslErrorHandler.proceed();//接受信任所有网站的证书
            }

            //拦截HTML页面中的点击事件
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        web.loadUrl(url);
                    }
                });


                return false;

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                super.onPageStarted(view, url, favicon);
            }
        });

        //加载页面进度条
        web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根
                if (newProgress == 100 && progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                    Log.e("当前url", web.getUrl() + "");
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
            }
        });
    }


    @SuppressLint("NewApi")
    private void initDatas() {
        String url = getIntent().getStringExtra("url");
        String title = getIntent().getStringExtra("title");

        if (title == null) {
            navigationBar.setVisibility(View.GONE);
        } else {
            navigationBar.setNaviTitle(title);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                web.loadUrl(url);
            }
        });


        WebSettings webSettings = this.web.getSettings();

        // 修改ua使得web端正确判断
        web.getSettings().setUserAgentString("youxiangju");

        //设置为可调用js方法
        webSettings.setJavaScriptEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

        web.evaluateJavascript("sum(1,2)", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                Log.e("dgj", "onReceiveValue value=" + value);
            }
        });
        web.addJavascriptInterface(this, "getLoadData");
    }

    private void initEvent() {
        navigationBar.setNavigationBarListener(this);
    }

    @Override
    public void navigationLeft() {
        finish();
    }

    @Override
    public void navigationRight() {
    }

    //设置返回键动作（防止按返回键直接退出程序)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e("当前url", web.getUrl() + "");
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (web.canGoBack()) {//当webview不是处于第一页面时，返回上一个页面
                if (exit == WebExit.FINISH.getCode()) {
                    super.finish();
                }
                if (exit == WebExit.PLAN_LIST.getCode()) {
                    if (web.getUrl().contains("createplan")) {
                        super.finish();

                    }
                    if (web.getUrl().contains("submitplan")) {
                        web.goBack();
                        return true;

                    }
                    if (web.getUrl().contains("result")) {
                        MerchantContainerActivity.start(this, false, MerchantType.PLAN.getCode());
                        super.finish();

                    }
                    if (web.getUrl().contains("planItem")) {
                        MerchantContainerActivity.start(this, false, MerchantType.PLAN.getCode());
                        super.finish();
                    } else {
                        this.finish();
                    }

                }
                if (exit == 4) {
                    MerchantContainerActivity.start(this, true, MerchantType.HOME.getCode());
                }
                else {
                    web.goBack();
                    return true;
                }

            } else {//当webview处于第一页面时,关闭web页面
                if (exit == 4) {
                    MerchantContainerActivity.start(this, true, MerchantType.HOME.getCode());
                }else{

                    super.finish();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @JavascriptInterface
    public void jumpWithPara(String data) {
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);
        String path = jsonObject.getString("path");
        int goodsName = jsonObject.getInteger("goodsName");
        if (path.equals("ToBePartner")) {
            PreparePurchaseActivity.start(this, goodsName+"");
        }


    }

    @JavascriptInterface
    public String getToken() {
        Log.w("tag", "token:" + TokenManager.INSTANCE.getMToken());
        return TokenManager.INSTANCE.getMToken();
    }

    @JavascriptInterface
    public void finishTist() {
        super.finish();
    }

    @JavascriptInterface
    public void jump(String page) {
        if (page.equals("homePage")) {
            MerchantContainerActivity.start(this, true, MerchantType.HOME.getCode());
        }
        if (page.equals("channellist")) {
            finish();
        }
        if (page.equals("planList")) {
            MerchantContainerActivity.start(this, false, MerchantType.PLAN.getCode());
        }

    }

    @Override
    public void finish() {
        if (exit == WebExit.FINISH.getCode()) {
            super.finish();
            return;
        }
        if (exit == WebExit.PLAN_LIST.getCode()) {
            if (web.getUrl().contains("createplan")) {
                super.finish();

            }
            if (web.getUrl().contains("submitplan")) {
                web.goBack();


            }
            if (web.getUrl().contains("result")) {
                MerchantContainerActivity.start(this, false, MerchantType.PLAN.getCode());
                super.finish();

            }
            if (web.getUrl().contains("planItem")) {
                MerchantContainerActivity.start(this, false, MerchantType.PLAN.getCode());
                super.finish();
            } else {
                super.finish();
            }
        } else {
            super.finish();
        }
    }

    @JavascriptInterface
    public void jump() {

    }

    @JavascriptInterface
    public void accessQRcode(String base64) {
        base64ToBitmap(base64);
    }

    @JavascriptInterface
    public void outLogin() {
        TokenManager.INSTANCE.clear();
        LoginActivity.start(this);
    }

    @JavascriptInterface
    public void gobackToMyRootView() {
        MerchantContainerActivity.start(this, true, MerchantType.HOME.getCode());
    }

    private String creatTime;

    //获取时间
    private void gainCurrenTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        creatTime = formatter.format(curDate);
    }

    //base64转图片
    public void base64ToBitmap(String base64Data) {
        Bitmap bitmap = null;

        try {
            byte[] bitmapArray = Base64.decode(base64Data.split(",")[1], Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
            addSignatureToGallery(bitmap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //保存图片
    File file;

    public boolean addSignatureToGallery(Bitmap signature) {
        boolean result = false;
        try {
            final File photo = new File(getAlbumStorageDir("优享钜邀请好友图片"), String.format(creatTime + ".jpg", System.currentTimeMillis()));
            file = photo;
            saveBitmapToJPG(signature, photo);
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri contentUri = Uri.fromFile(photo);
            mediaScanIntent.setData(contentUri);
            WebActivity.this.sendBroadcast(mediaScanIntent);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(photo);
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        stream.close();
        Toast.makeText(this, "图片保存成功", Toast.LENGTH_LONG).show();
    }

    public File getAlbumStorageDir(String albumName) {
        File file = new File(Environment.getExternalStorageDirectory(), albumName);
        if (!file.mkdirs()) {
            Log.e("SignaturePad", "Directory not created");
        }
        return file;
    }

}
